package com.gcxy.shop.common;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebFilter(urlPatterns="/*")
public class LoginFilter implements Filter{

	 private Logger logger=LoggerFactory.getLogger(getClass());
	
	public void destroy() {
		
	}
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		logger.debug("开始执行doFilter");
		try {
			//抽取参数
			//数据转换
			HttpServletRequest request=(HttpServletRequest)req;
			HttpServletResponse response=(HttpServletResponse)resp;//强制转换成HTTP类型，获取session信息
			HttpSession session=request.getSession();
			Object ouser=session.getAttribute("user");//检查用户是否登录
			String url=request.getRequestURI();//获取当前登录的地址
			logger.debug("当前请求的url:{}",url);
			//数据校验
			 if(ouser!=null) {
			    	logger.debug("已经登陆过了");
			    	chain.doFilter(request, response);//直接执行后面的请求信息
			    }else {
			    	logger.debug("没有登陆");
			    	if(url.contains("register")||url.contains("login")
			    	 ||url.contains("index")||url.contains("list")
			    	 ||url.contains("clothes")||url.contains("travel")
			    	 ||url.contains("phone")||url.contains("assets")
			    	 ||url.contains("find_step1")||url.contains("find_step2")
			    			) {
			    		chain.doFilter(request, response);
			    	}else {
			    		response.sendRedirect(request.getContextPath()+"/login.jsp");
			    	}
			    }
			//业务方法和处理
			//转发与重定向
			
		} catch (Exception e) {
			
		}
		
	}
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
